import React from 'react';
import { inject, observer } from 'mobx-react';
import { WeaForm, WeaSwitch, WeaTableNew } from 'comsMobx';
import { toJS } from 'mobx';
import {
  WeaTop,
  WeaLeftTree,
  WeaLeftRightLayout,
  WeaDropMenu,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaTab,
  WeaFormItem,
  WeaSearchGroup,
  WeaDialog,
  WeaBrowser,
  WeaLocaleProvider,
} from 'ecCom';
import * as Util from '../util';
import { Spin, Button, Modal, message } from 'antd';
import * as searchApi from '../apis/search';

const confirm = Modal.confirm;
const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;
import DocLog from './Tables/DocLog';
import DocShare from './Tables/DocShare';

const store = [
  'docMyDocStore',
  'docLatestDocStore',
  'docAllDocStore',
  'routing',
  'docDocLogStore',
  'docDocShareStore',
];
@inject('docMoreStore', ...store)

@observer
class More extends React.Component {
  constructor(props) {
    super(props);
    this.onOperatesClick = this.onOperatesClick.bind(this);
    this.mouldname = this.props.location.query.outDoc ? 'MoreOut' : 'More';
    this.state = {
      tabid: this.props.location.query.tabid,
      eid: this.props.location.query.eid,
      searchType: ['base', 'advanced']
    };
  }
  componentDidMount() {
    const { docMoreStore } = this.props;
    const { elementmore } = this.props.location.query.jsonstr ?
      { elementmore: this.props.location.query.jsonstr } : {};
    const isNew = this.props.location.query.isNew ? this.props.location.query.isNew : '0';
    const { tabid, eid } = this.state;
    const { getConditionInfo, doSearch, getRightMenu } = docMoreStore;
    let moreDecode = '';
    let elementParams = {};
    let Base64 = WeaTools.Base64;
    let moreEncode = elementmore;
    docMoreStore.setTitle(getLabel(19874, '文档中心'));
    docMoreStore.setIsNew(isNew);
    if (this.mouldname == 'More' && tabid && eid) {
      docMoreStore.getElementmore({ tabid, eid }).then(() => {
        elementParams = JSON.parse((toJS(docMoreStore.elementmore)));
        if (elementParams && elementParams.tabtitle) {
          docMoreStore.setTitle(elementParams.tabtitle);
        } else {
          docMoreStore.setTitle(getLabel(19874, '文档中心'));
          // 19874-文档中心
        }
        getConditionInfo(this.mouldname);
        getRightMenu(this.mouldname);
        doSearch(this.mouldname, { elementmore: docMoreStore.elementmore, isNew });
      });
    } else {
      if (moreEncode) {
        moreEncode = moreEncode.replace(/\ /g, '+');
        moreDecode = Base64.decode(moreEncode);
        docMoreStore.setElementmore(moreDecode);
        elementParams = JSON.parse(moreDecode);
        if (elementParams && elementParams.tabtitle) {
          docMoreStore.setTitle(elementParams.tabtitle);
        } else {
          docMoreStore.setTitle(getLabel(19874, '文档中心'));
          // 19874-文档中心
        }
      } else {
        docMoreStore.setTitle(getLabel(19874, '文档中心'));
      }

      getConditionInfo(this.mouldname);
      getRightMenu(this.mouldname);
      doSearch(this.mouldname, { elementmore: moreDecode, isNew });
    }
  }
  componentWillReceiveProps(nextProps) {
    const { docMoreStore } = nextProps;
    const { elementmore } = nextProps.location.query.jsonstr ?
      { elementmore: nextProps.location.query.jsonstr } : {};
    const isNew = nextProps.location.query.isNew ? nextProps.location.query.isNew : '0';
    let tabid = nextProps.location.query.tabid;
    let eid = nextProps.location.query.eid;
    const { getConditionInfo, doSearch, getRightMenu } = docMoreStore;
    this.setState({ tabid, eid });
    let moreDecode = '';
    let elementParams = {};
    let Base64 = WeaTools.Base64;
    let moreEncode = elementmore;
    docMoreStore.setTitle(getLabel(19874, '文档中心'));
    docMoreStore.setIsNew(isNew);
    if (this.mouldname == 'More' && tabid && eid) {
      docMoreStore.getElementmore({ tabid, eid }).then(() => {
        elementParams = JSON.parse((toJS(docMoreStore.elementmore)));
        if (elementParams && elementParams.tabtitle) {
          docMoreStore.setTitle(elementParams.tabtitle);
        } else {
          docMoreStore.setTitle(getLabel(19874, '文档中心'));
          // 19874-文档中心
        }
        getConditionInfo(this.mouldname);
        getRightMenu(this.mouldname);
        doSearch(this.mouldname, { elementmore: docMoreStore.elementmore, isNew });
      });
    } else {
      if (moreEncode) {
        moreEncode = moreEncode.replace(/\ /g, '+');
        moreDecode = Base64.decode(moreEncode);
        docMoreStore.setElementmore(moreDecode);
        elementParams = JSON.parse(moreDecode);
        if (elementParams && elementParams.tabtitle) {
          docMoreStore.setTitle(elementParams.tabtitle);
        } else {
          docMoreStore.setTitle(getLabel(19874, '文档中心'));
          // 19874-文档中心
        }
      } else {
        docMoreStore.setTitle(getLabel(19874, '文档中心'));
      }
      getConditionInfo(this.mouldname);
      getRightMenu(this.mouldname);
      doSearch(this.mouldname, { elementmore: moreDecode, isNew });
    }
  }
  componentWillUnmount() {
    const { docMoreStore } = this.props;
    const { setShowSearchAd } = docMoreStore;
    setShowSearchAd(false);
    // docMoreStore.clearTableDatas();
    // docMoreStore.setTitle("");
  }
  onRightMenuClick() {
    const Arr = [];
    return Arr;
  }
  getDocShare() {
    const { docMoreStore, docDocShareStore } = this.props;
    const { showDocShare, shareDocId } = docMoreStore;
    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@eun18m`}
        className="wea-doc-share-modal"
        title={getLabel(1985, '文档共享')}
        style={{ width: 800, height: 'auto' }}
        maskClosable={false}
        icon="icon-coms-doc"
        iconBgcolor="#df583a"
        visible={showDocShare}
        onCancel={() => docMoreStore.setState({ showDocShare: false })}
      >
        <DocShare ecId={`${this && this.props && this.props.ecId || ''}_DocShare@c2cfln`} docid={shareDocId} />
      </WeaDialog>
    );
  }
  getDocLog() {
    const { docMoreStore, docDocLogStore } = this.props;
    const { showDocLog, logDocId } = docMoreStore;
    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@vprpjv`}
        className="wea-doc-log-modal"
        title={getLabel(21990, '文档日志')}
        style={{ width: 720, height: 'auto' }}
        maskClosable={false}
        icon="icon-coms-doc"
        iconBgcolor="#df583a"
        visible={showDocLog}
        onCancel={this.onDocLogDiaCancel}
      >
        <DocLog ecId={`${this && this.props && this.props.ecId || ''}_DocLog@14xzcq`} docid={logDocId} />
      </WeaDialog>
    );
  }
  onDocLogDiaCancel=() => {
    const {docMoreStore,docDocLogStore}=this.props;
    docMoreStore.setState({ showDocLog: false });
    docDocLogStore.setState({ viewcondition: 0, showSearchAd: false });
  }

  doDocDelete(params) {
    const { docMoreStore } = this.props;
    const { doSearch, elementmore } = docMoreStore;
    // const {elementmore} = this.props.location.query.jsonstr ?
    //                         { elementmore: this.props.location.query.jsonstr }  : {};
    const isNew = this.props.location.query.isNew ? this.props.location.query.isNew : '0';
    const mouldname = this.mouldname;
    searchApi.doDeleteWarm().then((data) => {
      confirm({
        content: (
          <span>
            {data.title}
            {
              data.subTitle ? <span style={{ color: 'red' }}>({data.subTitle})</span> : null
            }
          </span>
        ),
        onOk: () => {
          searchApi.doDelete(params).then((_data) => {
            if (Number(_data.status) == 1) {
              doSearch(mouldname, { elementmore, isNew });
              message.success(_data.msg);
            } else {
              message.error(_data.msg);
            }
          });
        },
        onCancel() { },
      });
    });
  }
  getRightMenu() {
    const { docMoreStore } = this.props;
    const { rightMenu, doSearch, form, showSearchAd
      , setShowSearchAd, comsWeaTableStore
      , setIsNew
      , quickSearchValue } = docMoreStore;
    const { elementmore } = this.props.location.query.jsonstr ?
      { elementmore: this.props.location.query.jsonstr } : {};
    const isNew = this.props.location.query.isNew ? this.props.location.query.isNew : '0';
    let btnArr = [];
    const selectedRowKeys = comsWeaTableStore.selectedRowKeys;
    const mouldname = this.mouldname;
    rightMenu.slice().forEach((m) => {
      let disabled = selectedRowKeys.length === 0;
      let onClick = () => { };
      let content = m.menuName;
      let Base64 = WeaTools.Base64;
      let moreEncode = elementmore;
      let moreDecode = '';
      if (moreEncode) {
        moreEncode = moreEncode.replace(/\ /g, '+');
        moreDecode = Base64.decode(moreEncode);
      }
      if (m.type === 'BTN_SEARCH') {
        disabled = false;
        onClick = () => {
          if (showSearchAd) {
            doSearch(this.mouldname, { elementmore: docMoreStore.elementmore, isNew, ...form.getFormParams() });
            setShowSearchAd(false);
          } else {
            doSearch(this.mouldname, { elementmore: docMoreStore.elementmore, isNew, docsubject: quickSearchValue, ...form.getFormParams() });
          }
        };
      }
      btnArr.push({
        key: m.type,
        icon: <i className={m.menuIcon} />,
        content,
        disabled,
        onClick,
      });
    });
    return btnArr;
  }
  getButtons() {
    const { docMoreStore } = this.props;
    const { rightMenu, comsWeaTableStore } = docMoreStore;
    const selectedRowKeys = comsWeaTableStore.selectedRowKeys;
    let btnArr = [];
    rightMenu.slice().forEach((m) => {
      let onClick = () => { };
      let content = m.menuName;
      let disabled = selectedRowKeys.length === 0;
      if (m.isTop === '1') {
        btnArr.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@yur9dl@${m.menuName}`} type="primary" disabled={disabled} onClick={onClick}>{content}</Button>);
      }
    });
    return btnArr;
  }
  onSearch = () => {
    const { docMoreStore } = this.props;
    const { form, doSearch, setShowSearchAd, elementmore, setIsNew } = docMoreStore;
    const mouldname = this.mouldname;
    doSearch(mouldname, { elementmore, setIsNew, ...form.getFormParams() });
    setShowSearchAd(false);
  }
  getSearchs() {
    const { docMoreStore } = this.props;
    const { conditioninfo, form } = docMoreStore;
    const { isFormInit } = form;
    let group = [];
    const formParams = form.getFormParams();
    isFormInit && toJS(conditioninfo).map((c) => {
      let items = [];
      c.items.map((fields) => {
        if (fields.isQuickSearch) {
          this.quickSearchPara = fields.domkey[0];
        }
        items.push({
          com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@l0c6m8@${fields.domkey[0]}`}
            label={`${fields.label}`}
            labelCol={{ span: `${fields.labelcol}` }}
            wrapperCol={{ span: `${fields.fieldcol}` }}
          >
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@cqucus@${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams} onEnterSearch={this.onSearch} />
          </WeaFormItem>),
          colSpan: 1,
        });
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@uzcxhf@${c.title}`} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />);
    });
    return group;
  }
  getTabButtonsAd() {
    const { docMoreStore } = this.props;
    const { form, doSearch, setShowSearchAd, elementmore, isNew } = docMoreStore;
    const btns = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7pc9us@search`} type="primary"
        onClick={this.onTabSearchClick}
      >{getLabel(197, '搜索')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@71tydl@reset`} type="ghost" onClick={this.onTabResetClick}>{getLabel(2022, '重置')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bu2gh9@cancel`} type="ghost"
        onClick={this.onTabCancelClick}
      >{getLabel(31129, '取消')}</Button>,
    ];
    return btns;
  }
  onTabSearchClick = () => {
    const { docMoreStore } = this.props;
    const { form, doSearch, setShowSearchAd, elementmore, isNew } = docMoreStore;
    const mouldname = this.mouldname;
    doSearch(mouldname, { elementmore, isNew, ...form.getFormParams() });
    setShowSearchAd(false);
  }
  onTabResetClick = () => {
    const { docMoreStore } = this.props;
    const { form } = docMoreStore;
    form.reset();
  }

  onTabCancelClick = () => {
    const { setShowSearchAd } = this.props.docMoreStore;
    setShowSearchAd(false);
  }

  onOperatesClick(record, index, operate) {
    const { docMoreStore, docDocLogStore, docDocShareStore } = this.props;
    const funName = operate.href.replace(/(javascript\:)|(\(\))/g, () => '');
    if (funName === 'doEdit') {
      Util.openWindow(
        `/spa/document/index.jsp?id=${record.id}&isEdit=1&router=1#/main/document/edit`,
      );
    } else if (funName === 'doMuliDelete') {
      this.doDocDelete({ docid: record.id });
    } else if (funName === 'doDocShare') {
      docMoreStore.setState({ showDocShare: true, shareDocId: record.id });
      docDocShareStore.doSearch('DocShare', { docid: record.id })
        .canShareAddEdit({ docid: record.id });
    } else if (funName === 'doDocViewLog') {
      docMoreStore.setState({ showDocLog: true, logDocId: record.id });
      docDocLogStore.getTabInfo()
        .getRightMenu('DocLog')
        .getConditionInfo('DocLog')
        .doSearch('DocLog', { viewcondition: 0, docid: record.id });
    }
  }

  collectParams = () => {
    const { docMoreStore } = this.props;
    return {
      favname: docMoreStore.title,
      favouritetype: 2,
      objid: 0,
      importantlevel: 1,
      link: 'wui/index.html#/main/document/more',
    }
  }

  dropMenuProps = () => {
    const { docMoreStore } = this.props;
    return {
      collectParams: {
        favname: docMoreStore.title,
        favouritetype: 2,
        objid: 0,
        importantlevel: 1,
        link: 'wui/index.html#/main/document/more',
      },
    }
  }

  hideSearchAd = () => {
    const { docMoreStore } = this.props;
    const { setShowSearchAd } = docMoreStore;
    setShowSearchAd(false);
  }

  searchsBaseValue = () => {
    const { docMoreStore } = this.props;
    const { form } = docMoreStore;
    return form.getFormParams()[this.quickSearchPara] || '';
  }

  setShowSearchAd = () => {
    const { docMoreStore } = this.props;
    const { showSearchAd } = docMoreStore;
    docMoreStore.setShowSearchAd(!showSearchAd);
  }

  onTabSearch = (value) => {
    const { form, elementmore, setIsNew,doSearch } = this.props.docMoreStore;
    const mouldname = this.mouldname;
    doSearch(mouldname, { elementmore, setIsNew, docsubject: value, ...form.getFormParams() });
  }

  onTabSearchChange = (value) => {
    const { form, setQuickSearchValue } = this.props.docMoreStore;
    form.updateFields({ [this.quickSearchPara]: { value } });
    setQuickSearchValue(value);
  }

  paginationProps = () => {
    const mouldname = this.mouldname;
    return mouldname == 'MoreOut' ? {
      pageSizeOptions: ['10'],
    }
      :
      {}
  }

  render() {
    const { docMoreStore } = this.props;
    let { comsWeaTableStore, loading, showSearchAd
      , setShowSearchAd, doSearch, form, elementmore, setIsNew, tabData
      , treeData, setElementmore
      , getRightMenu, setQuickSearchValue } = docMoreStore;
    const loadingNow = loading || comsWeaTableStore.loading;
    const mouldname = this.mouldname;
    return (
      <div className="wea-doc-dummy">
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@p6t70y`}
          collectParams={this.collectParams()}
          datas={this.getRightMenu()}
          onClick={this.onRightMenuClick}
        >
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@ypy9lg`}
            title={docMoreStore.title}
            loading={docMoreStore.loading}
            icon={<i className="icon-coms-doc" />}
            iconBgcolor="#df583a"
            buttons={this.getButtons()}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            dropMenuProps={this.dropMenuProps()}
            onDropMenuClick={this.onRightMenuClick}
          >
            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@2gf23q`}
              searchType={this.state.searchType}
              searchsAd={this.getSearchs()}
              showSearchAd={showSearchAd}
              buttonsAd={this.getTabButtonsAd()}
              hideSearchAd={this.hideSearchAd}
              searchsBaseValue={this.searchsBaseValue()}
              setShowSearchAd={this.setShowSearchAd}
              onSearch={this.onTabSearch}
              onSearchChange={this.onTabSearchChange}
            />
            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@q9i6cf`}
              comsWeaTableStore={comsWeaTableStore}
              hasOrder={true}
              needScroll={true}
              showmethod={true}
              paginationProps={this.paginationProps()}
              onOperatesClick={this.onOperatesClick}
            />
          </WeaTop>
        </WeaRightMenu>
        {this.getDocShare()}
        {this.getDocLog()}
      </div>
    );
  }
}

export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@g4izb9`} msg={props.error ? props.error : getLabel(385218, '对不起，该页面异常，请联系管理员！')} />,
  { error: '' },
)(More);

